import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController, ModalController } from 'ionic-angular';
import { DeviceProvider } from '../../providers/service/device'
import { HomeListPage } from './home-list/home-list'
// import { DynamicGisBtnDirective } from '../../directives/dynamic-gis-btn/dynamic-gis-btn'
declare var AMap;

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {

    @ViewChild('map_container') map_container: ElementRef;
    @ViewChild('info_window') info_window: ElementRef;
    @ViewChild('searchBar_wrap') searchBar_wrap: ElementRef;

    statisData = {    //统计信息
        totalNum: 0,
        manualMode: 0,
        stopMode: 0,
        fault: 0
    };
    mapObj: any;    //地图对象

    infoWindow;    //窗体信息
    devList = [];  //设备列表
    deviceObj = null;  //设备对象
    infoLoading = false;   //窗体loading

    cluster = null;   //点聚焦
    markers = [];       //点集合
    diaDeviceArr = [];  //设备数组

    searchKey;    //搜索关键字


    constructor(public navCtrl: NavController,
        public modalCtrl: ModalController,
        public deviceProvider: DeviceProvider) {

    }

    //窗口弹出
    presentModal(arr) {
        let modal = this.modalCtrl.create(HomeListPage, { diaDeviceArr: arr});
        modal.onDidDismiss(data => {
            if(data != ''){
                this.markerClickHandle(data);
            }
        });
        modal.present();

    }
    ionViewDidLoad() {
        // ionViewDidLoad() {
        //初始化页面
        this.mapObj = new AMap.Map(this.map_container.nativeElement, {
            zoom: 5,
            center: [109.7314453125, 32.6208701832],
            mapStyle: 'macaron'
        });
        this.mapObj.on("click", (e) => {
            if (this.infoWindow) { this.infoWindow.close(); }
        })
        AMap.event.addListener(this.mapObj, "complete", this.completeEventHandler());
    }

    completeEventHandler() {

        this.deviceProvider.getStateCount().then(res => {
            this.statisData = { ...this.statisData, ...res };
        }, err => {

        });

        this.deviceProvider.getGisList({}).then((res: any) => {
            if ((res instanceof Array)) {
                this.devList = res;
                this.initMarkers();
            }
        }, err => {

        });

    }
    initMarkers() {
        for (let i = 0; i < this.devList.length; i++) {
            let devItem = this.devList[i];
            if (!devItem || !devItem.longitude || !devItem.latitude) {
                continue;
            }
            let iconPath = '';
            var _preIconPath = "assets/imgs/",
                iconOnline = _preIconPath + "point_online.png",
                iconOffline = _preIconPath + "point_offline.png",
                iconWarning = _preIconPath + "point_warning.png";

            switch (devItem.status) {
                case 0: iconPath = iconOffline; break;
                case 1:
                case 2:
                case 3:
                    iconPath = iconOnline; break;
                case 99:
                    iconPath = iconWarning; break;
            }
            //   <p>${devItem.physicalCode}</p>
            let tempHtml = `<div class="gis-ctBox">
                          <img src="${iconPath}">
                      </div>`;
            let marker = new AMap.Marker({
                map: this.mapObj,
                extData: devItem,
                position: [devItem.longitude, devItem.latitude],      //经大 纬小
                content: tempHtml
            });

            marker.on('click', (e) => {
                // this.markerParam = e.target.getExtData();
                return this.markerClickHandle(e.target.getExtData());
            });
            this.markers.push(marker);

        }
        this.mapObj.setFitView(this.markers);

        //添加点聚合
        this.addCluster();
    }


    markerClickHandle(obj) {

        this.infoLoading = true;
        this.deviceObj = null;
        this.deviceProvider.getDetail(obj.id).then(res => {
            this.deviceObj = res;
            console.log(res);
            this.infoLoading = false;
        }, err => {
            this.infoLoading = false;
        })

        // console.log(this.info_window.nativeElement)
        setTimeout(res => {
            if (this.infoWindow) {
                this.infoWindow.setContent(this.info_window.nativeElement);
            } else {

                this.infoWindow = new AMap.InfoWindow({
                    isCustom: true,  //使用自定义窗体
                    content: this.info_window.nativeElement,
                    offset: new AMap.Pixel(63, -30)//-113, -140
                });

            }
            this.infoWindow.open(this.mapObj, [obj.longitude, obj.latitude]);
        }, 0)

    }

    addCluster() {
        var _this = this;
        if (_this.cluster) {
            _this.cluster.setMap(null);
        }

        var sts=[{
            url:"assets/imgs/img-cluster.png",
            size:new AMap.Size(32,32),
            offset:new AMap.Pixel(-16,-30),
            textColor:'#ffffff'
        },
        {
            url:"assets/imgs/img-cluster.png",
            size:new AMap.Size(32,32),
            offset:new AMap.Pixel(-16,-30),
            textColor:'#ffffff'
        },
        {
            url:"assets/imgs/img-cluster.png",
            size:new AMap.Size(32,32),
            offset:new AMap.Pixel(-16,-30),
            textColor:'#ffffff'
        }];
        _this.mapObj.plugin(["AMap.MarkerClusterer"], function() {
            _this.cluster = new AMap.MarkerClusterer(_this.mapObj, _this.markers, {
                minClusterSize: 2,
                zoomOnClick: false,
                styles:sts
            });
//
                   //点击查看车辆
            _this.cluster.on("click", function(cluster){
                _this.diaDeviceArr = [];
                for(let val of cluster.markers){
                    //console.log(val.getExtData());
                    _this.diaDeviceArr.push(val.getExtData())
                }
                _this.presentModal(_this.diaDeviceArr);
               // _this.diaVisible = true;
            });
            //getMarkers
        });
    }


    //搜搜
    searchOnHandler(e) {
        if (e.type == "input") {
            if (this.infoWindow) { this.infoWindow.close(); }
            this.searchBar_wrap.nativeElement.style.display = "block";
        }
    }
    //取消搜索
    searchOnCancel(e) {
        this.searchBar_wrap.nativeElement.style.display = "none";
    }

    //聚焦某一个
    focusItem(item) {
        this.searchBar_wrap.nativeElement.style.display = "none";
        this.markerClickHandle(item)
    }

    setMapFitView() {
        this.mapObj.setFitView();
    }

}
